﻿using Microsoft.Win32;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Utility.QRCode_F4;
using ZXing;
using ZXing.Common;
using ZXing.Rendering;

namespace GBT_Tool_v4._0.ToolHelps
{
    public class Tools
    {
        public Bitmap GenerateBarcode(string text, uint heigth)
        {
            BarCode.Code128 _Code = new BarCode.Code128();
            _Code.Height = heigth;
            _Code.ValueFont = new Font("宋体", 20);
            Bitmap map = _Code.GetCodeImage(GetIdNumber(6, text) + DateTime.Now.ToString("yyyyMMddHHmmssfff"), BarCode.Code128.Encode.Code128A);
            return map;
        }

        public void GenerateBarcode(string text, int companyId)
        {
            BarCode.Code128 _Code = new BarCode.Code128();
            _Code.ValueFont = new Font("宋体", 20);
            Bitmap map = _Code.GetCodeImage(text, BarCode.Code128.Encode.Code128A);

            var folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Photos");

            //删除子目录下的所有没有被占用的文件
            deleteDirFiles(folder);

            var fileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Photos/{companyId.ToString()}");

            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            var path = Path.Combine(fileFolder, $@"{text}bar.png");
            if (!File.Exists(path))
            {
                FileStream NewFile = File.Create(path);
                MemoryStream mstream = new MemoryStream();
                map.Save(mstream, ImageFormat.Png);
                byte[] byData = new byte[mstream.Length];
                mstream.Position = 0;
                mstream.Read(byData, 0, byData.Length);
                mstream.Close();
                NewFile.Write(byData, 0, byData.Length);
                NewFile.Close();
            }
        }

        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="text"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public Bitmap GenerateBarcode(string text, int width, int height)
        {
            BarcodeWriter<Bitmap> writer = new BarcodeWriter<Bitmap>();
            //使用ITF 格式，不能被现在常用的支付宝、微信扫出来
            //如果想生成可识别的可以使用 CODE_128 格式
            //writer.Format = BarcodeFormat.ITF;
            writer.Format = BarcodeFormat.CODE_128;
            EncodingOptions options = new EncodingOptions()
            {
                Width = width,
                Height = height,
                Margin = 2
            };
            writer.Options = options;
            //渲染器
            BitmapRenderer bitmapRenderer = new BitmapRenderer();
            writer.Renderer = bitmapRenderer;
            Bitmap map = writer.Write(text);
            return map;
        }

        //判断文件是否被占用
        private bool IsFileInUse(string fileName)
        {
            bool inUse = true;

            FileStream fs = null;
            try
            {

                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                inUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)

                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }

        /// <summary>
        /// 删除目录下的所有文件及文件夹
        /// </summary>
        /// <param name="strPath"></param>
        private void deleteDirFiles(string strPath)
        {
            if (!Directory.Exists(strPath))
                Directory.CreateDirectory(strPath);

            //删除这个目录下的所有子目录
            if (Directory.GetDirectories(strPath).Length > 0)
            {
                foreach (string var in Directory.GetDirectories(strPath))
                {
                    //Directory.Delete(var, true);
                    //删除这个目录下的所有文件
                    if (Directory.GetFiles(var).Length > 0)
                    {
                        foreach (string file in Directory.GetFiles(var))
                        {
                            if (!IsFileInUse(file))
                                File.Delete(file);
                        }
                    }
                }
            }
        }

        public string GetIdNumber(int num, string id)
        {
            return id.ToString().PadLeft(num, '0');
        }

        /// <summary>
        /// 创建二维码文件
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="content"></param>
        public void CreateQRCodeFile(int companyId, string content)
        {
            QRCodeEncoder encoder = new QRCodeEncoder();
            encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;//编码方法(注意：BYTE能支持中文，ALPHA_NUMERIC扫描出来的都是数字)
            encoder.QRCodeScale = 4;//大小
            encoder.QRCodeVersion = 0;//版本(注意：设置为0主要是防止编码的字符串太长时发生错误)
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
            
            string qrdata = GetIdNumber(6, content) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            Bitmap bp = encoder.Encode(qrdata, Encoding.GetEncoding("UTF-8"));

            var folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Photos");

            //删除子目录下的所有没有被占用的文件
            deleteDirFiles(folder);

            var fileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Photos/{companyId.ToString()}");

            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            var path = Path.Combine(fileFolder, $@"{content}.png");
            if (!File.Exists(path))
            {
                FileStream NewFile = File.Create(path);
                MemoryStream mstream = new MemoryStream();
                bp.Save(mstream, ImageFormat.Png);
                byte[] byData = new byte[mstream.Length];
                mstream.Position = 0;
                mstream.Read(byData, 0, byData.Length);
                mstream.Close();
                NewFile.Write(byData, 0, byData.Length);
                NewFile.Close();
            }
        }

        public string AutoStart()
        {
            #region 设置开机自启
            string strName = AppDomain.CurrentDomain.BaseDirectory + "TakeFoodSystem.exe";//获取要自动运行的应用程序名
            if (!File.Exists(strName))//判断要自动运行的应用程序文件是否存在
                return "";
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);//获取应用程序文件名，不包括路径
            RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//检索指定的子项
            if (registry == null)//若指定的子项不存在
                registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//则创建指定的子项
            registry.SetValue(strnewName, strName);//设置该子项的新的“键值对”
            return "成功设置开机自动启动";
            #endregion
        }

        public string UnAutoStart()
        {
            #region 取消开机自启
            string strName = AppDomain.CurrentDomain.BaseDirectory + "TakeFoodSystem.exe";//获取要自动运行的应用程序名
            if (!System.IO.File.Exists(strName))//判断要取消的应用程序文件是否存在
                return "";
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);///获取应用程序文件名，不包括路径
            RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//读取指定的子项
            if (registry == null)//若指定的子项不存在
                registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//则创建指定的子项
            registry.DeleteValue(strnewName, false);//删除指定“键名称”的键/值对
            return "成功取消开机自动启动";
            #endregion
        }
    }
}
